import os
import subprocess
import sys
import logging

exe_path = os.path.dirname(os.path.abspath(__file__))
ipmi_path = os.pathsep + os.path.join(exe_path, 'ipmitool')
os.environ['PATH'] += ipmi_path
sys.path.append(exe_path)

from PyQt5 import QtWidgets
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import *

LOG = logging.getLogger()


def get_execute_cmd_result(cmd):
    try:
        LOG.debug("execute cmd={}".format(cmd))
        p = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
        return bytes.decode(p).strip()
    except Exception as e:
        err_msg = "execute cmd failed, cmd={}, error={}".format(cmd, e)
        LOG.warning(err_msg)
        raise Exception(err_msg)


class UpdateSvgPicture(QWidget):
    SVG_Changed = pyqtSignal()
    Picture_Changed = pyqtSignal()

    def __init__(self):
        super(QWidget, self).__init__()
        self.resize(1000, 618)
        self.check_file_time = 0.5
        self.svg_picture_time = 0
        self.other_picture_time = 0
        self.setWindowTitle("动态更新图片")
        self.setWindowIcon(QIcon('update_fsm.ico'))
        self.layout = QVBoxLayout(self)
        # self.layout.setHorizontalSpacing(20)
        self.set_ipmi_account_view()
        self.set_ipmi_control_view()
        self.history_record = QTextEdit()
        self.layout.addWidget(self.history_record)

    def execute_ipmi_cmd(self):
        ipmi_cmd = {
            'power on': 'power on',
            'power off': 'power off',
            'reboot': 'power reset',
            'pxe reboot': 'chassis bootparam set bootflag force_pxe',
            'bios reboot': 'chassis bootparam set bootflag force_bios',
            'disk reboot': 'chassis bootparam set bootflag force_disk'}
        ipmi_cmd_str = ipmi_cmd.get(self.select_ipmi_control.currentText())
        ipmi_input = self.ipmi_input.text()
        user_input = self.user_input.text()
        pwd_input = self.pwd_input.text()
        if all([ipmi_input, user_input, pwd_input]) is False:
            self.show_message('ipmi/user/pwd 不能为空')
            return
        cmd = 'ipmitool -I lanplus -H {} -U {} -P {} {}'.format(
            self.ipmi_input.text(), self.user_input.text(), self.pwd_input.text(), ipmi_cmd_str)
        try:
            self.ipmi_button.setText('execute processing')
            get_execute_cmd_result(cmd)
        except Exception as e:
            self.ipmi_button.setText('execute failed')
            self.show_message(str(e))
        finally:
            self.ipmi_button.setText('execute ipmi command')

    def set_ipmi_account_view(self):
        layout = QHBoxLayout()
        ipmi_label = QLabel('ipmi')
        user_label = QLabel('user')
        pwd_label = QLabel('pwd')
        self.ipmi_input = QLineEdit()
        self.user_input = QLineEdit()
        self.pwd_input = QLineEdit()
        layout.addWidget(ipmi_label)
        layout.addWidget(self.ipmi_input)
        layout.addWidget(user_label)
        layout.addWidget(self.user_input)
        layout.addWidget(pwd_label)
        layout.addWidget(self.pwd_input)
        self.layout.addLayout(layout)

    def show_message(self, err_msg):
        QtWidgets.QMessageBox.warning(self, "错误", err_msg, QtWidgets.QMessageBox.Cancel)

    def set_ipmi_control_view(self):
        layout = QHBoxLayout()
        self.select_ipmi_control = QComboBox()
        self.select_ipmi_control.setObjectName('ipmi control')
        self.select_ipmi_control.addItems(['power on', 'power off', 'reboot',
                                           'pxe reboot', 'disk reboot', 'bios reboot'])
        self.ipmi_button = QPushButton('execute ipmi command')
        self.ipmi_button.clicked.connect(self.execute_ipmi_cmd)
        layout.addWidget(self.select_ipmi_control)
        layout.addWidget(self.ipmi_button)
        # spaceItem = QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding)
        # layout.addSpacerItem(spaceItem)
        connect_button = QPushButton('connect kvm')
        layout.addWidget(connect_button)
        self.layout.addLayout(layout)


if __name__ == "__main__":
    import cgitb

    cgitb.enable()
    app = QtWidgets.QApplication(sys.argv)
    my = UpdateSvgPicture()
    my.show()
    sys.exit(app.exec_())
